package com.horoscope.astrology.zodiac.signs.free.utils

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.hardware.display.DisplayManager
import android.os.Build
import android.os.PowerManager
import android.view.Display
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.MmoApplication
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.activity.MainActivity
import com.horoscope.astrology.zodiac.signs.free.activity.QuoteActivity
import com.horoscope.astrology.zodiac.signs.free.activity.SplashActivity

/**
 * 消息通知工具
 */
object NotificationUtil {

    private const val TAG = "NotificationUtil"
    var notifyManager: NotificationManager? = null
    val mContext = MmoApplication.getInstance()

    fun notifyByAlarmByService(context: Context) {
        createNotification(
            arrayOf(
                Intent(context, MainActivity::class.java),
                Intent(context, QuoteActivity::class.java)
            ),
            AppSettingManager.readQuote("quote_bean")!!.text.ifEmpty {
                context.getString(
                    R.string.text_daily_quote_sub_text
                )
            }, "Today’s Quote", context
        )
    }

    // create Notification
    private fun createNotification(
        intents: Array<Intent>, text: String?, title: String?, context: Context
    ) {
        val mainPaddingIntent = PendingIntent.getActivities(
            context, 0, intents, PendingIntent.FLAG_UPDATE_CURRENT
        )
        val builder = NotificationCompat
            .Builder(context, SysUtils.createNotificationChannel(context, isScreenOn()))
            .setSmallIcon(
                if (Rom.isEmui || Rom.isMiui || Rom.isOppo || Rom.isVivo) R.mipmap.ic_launcher_new else R.mipmap.icon_alpha_push
            )
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.mipmap.ic_launcher_new
                )
            )
            .setStyle(NotificationCompat.BigTextStyle().bigText(text))
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(text)
            .setContentIntent(mainPaddingIntent)
            .setDefaults(Notification.DEFAULT_ALL)
            .setColor(ContextCompat.getColor(context, R.color.purple_5))

        notifyManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        notifyManager!!.notify(((Math.random() * 9 + 1) * 100000).toInt(), builder.build())
    }

    @SuppressLint("ObsoleteSdkInt")
    private fun isScreenOn(): Boolean {
        if (Build.VERSION.SDK_INT >= 20) {
            val dm = MmoApplication.getInstance()
                .getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
            val displays = dm.displays
            for (display in displays) {
                if (display.state == Display.STATE_ON || display.state == Display.STATE_UNKNOWN)
                    return true
            }
        }

        val powerManager =
            MmoApplication.getInstance().getSystemService(Context.POWER_SERVICE) as PowerManager
        if (powerManager.isInteractive) {
            return true
        }
        return false
    }

    fun createThree(context: Context, type: Int, name: String) {
        val intent = Intent(context, SplashActivity::class.java)
        intent.putExtra("Alarm", true)
        intent.putExtra("workName", name)
        intent.putExtra("alarm_type", type)
        val mainPaddingIntent = PendingIntent.getActivities(
            context, type, arrayOf(intent), PendingIntent.FLAG_UPDATE_CURRENT
        )
        val views = RemoteViews(context.packageName, R.layout.layout_notification)
        when (type) {
            1011 -> { // name
                views.setTextViewText(R.id.tv_title, "Our astrologers have something to tell you.")
            }
            1012 -> { // relation
                views.setTextViewText(R.id.tv_title, "Do you know how to act with your lover？")
            }
            1013 -> { // birthChat
                views.setTextViewText(R.id.tv_title, "Our astrologers have seen a lot！")
            }
        }
        views.setTextViewText(R.id.tv_content, getContent(type))
        if (AppSettingManager.readObject("user_info") != null) {
            views.setImageViewResource(R.id.iv_icon,ConstellationUtil.getDrawableIdByName(AppSettingManager.readObject("user_info")!!.constellationName))
        }else{
            views.setImageViewResource(R.id.iv_icon,R.mipmap.icon_alpha_push)

        }
        views.setTextViewText(R.id.btn_notification_ok, "View more")
        views.setOnClickPendingIntent(R.id.btn_notification_ok, mainPaddingIntent)


        val builder = NotificationCompat
            .Builder(context, SysUtils.createNotificationChannel(context, isScreenOn()))
            .setContent(views)
            .setSmallIcon(
                if (Rom.isEmui || Rom.isMiui || Rom.isOppo || Rom.isVivo) R.mipmap.ic_launcher_new else R.mipmap.icon_alpha_push
            )
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.mipmap.ic_launcher_new
                )
            )
            .setAutoCancel(true)
            .setContentIntent(mainPaddingIntent)
            .setDefaults(Notification.DEFAULT_ALL)
            .setColor(ContextCompat.getColor(context, R.color.purple_5))

        notifyManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (type == 0) {
            notifyManager!!.notify(((Math.random() * 9 + 1) * 100000).toInt(), builder.build())
        } else {
            notifyManager!!.notify(type, builder.build())
        }
    }

    private val namePush = arrayOf(
        "What‘s scores between you and your partner.",
        "Every name has its meaning, test your and your friends."
    )

    private val relationPush = arrayOf(
        "Check your and your partner's horoscope to know all the secrets",
        "We were surprised with your horoscope",
        "Test who are your truely friend"
    )

    private val birthChatPush = arrayOf(
        "We know what awaits you",
        "Your professional life predictions are ready"
    )

    // 随机获取
    private fun getContent(id: Int): String {
        val strArray = when (id) {
            1011 -> namePush
            1012 -> relationPush
            1013 -> birthChatPush
            else -> namePush
        }
        val index = (strArray.indices).random()
        return if (index < strArray.size) {
            strArray[index]
        } else {
            strArray[0]
        }
    }

    // 取消指定闹钟
    fun cancelNotification(id: Int) {
        if (notifyManager != null) {
            notifyManager!!.cancel(id)
        } else {
            val manager =
                mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.cancel(id)
        }
    }

}